const app = require('./config/koa');
const config = require('./config/db_config.json');
const query = require('./core/mysql');
const Store = require('./util/redis-store');
const draftSocket = require('./util/draft-socketio');
const redisMysql = require('./util/redis-mysql');
const session = require('koa-session2');
const http = require('http');
const fs = require('fs');
const path = require('path');
var routes = require('./routes/index');
var users = require('./routes/user/user');

app.use(session({
  store: new Store(config.redis),
  ttl: 2 * 60 * 60 * 1000
}));

app.use(async(ctx, next) => {
  ctx.execSql = query;
  // ctx.set('Access-Control-Allow-Origin', config.accessControlAllowOrigin);
    let {method, url, header} = ctx.request;

    ctx.set('Access-Control-Allow-Origin', 'http://localhost:3000');

    if (method.toLowerCase() === 'options') {
        ctx.set('Access-Control-Allow-Credentials', 'true');
        ctx.set('Access-Control-Allow-Methods', 'POST,GET,OPTIONS,PUT,DELETE');
        ctx.set('Access-Control-Allow-Headers', 'cache-control,content-type,hash-referer,x-requested-with');

        ctx.body = '';
        return false;
    }
  await next();
});

// routes
// app.use('/', routes);
// app.use('/verify', verify);


fs.readdirSync(path.join(__dirname, 'routes')).forEach(function (file) {
    if (~file.indexOf('.js')) {
      app.use(require(path.join(__dirname, 'routes', file)).routes());
    }
});

// app.use(function (ctx, next) {
//    ctx.redirect('/404.html');
// });

app.on('error', (error, ctx) => {
  console.log('something error ' + JSON.stringify(ctx.onerror));
  ctx.redirect('/500.httml');
})

const server = http.createServer(app.callback())
	.listen(config.port)
	.on('listening', function () {
	  console.log('server listening on: ' + config.port);
  });

// 初始化websocket
draftSocket.initSocket(server);

// 初始化定时任务
redisMysql.redisToMysqlTask();
//F4jEAsk08C9RJ2zpMbwOqDCnJso1SqIYmakqvNRR/nL/z6mXOynAi2+G5YoTRs8OzaFsqgnwUaK6NQWx0oqrOQ==
